package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.example.demo.common.AjaxResult;
import com.example.demo.common.AppVariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.model.UserInfo;
import com.example.demo.model.vo.UserInfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserService userService;
    @Resource
    private ArticleService articleService;

    @RequestMapping("/reg")
    public AjaxResult register(UserInfo userInfo) {
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) {
            return AjaxResult.fail(-1, "非法参数");
        }
        userInfo.setPassword(PasswordUtils.encrypt(userInfo.getPassword()));
        return AjaxResult.success(userService.register(userInfo));
    }

    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request, String username, String password, String verify) {

        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "非法请求");
        }

        UserInfo userInfo = userService.getUserByName(username);

        if (userInfo != null && userInfo.getId() > 0) {
            if (PasswordUtils.check(password, userInfo.getPassword())) {
                //System.out.println(verify.equals(stringRedisTemplate.opsForValue().get("code")));
                userInfo.setPassword("");

                // 存储session
                HttpSession session = request.getSession();
                session.setAttribute("USER_SESSION_KEY", userInfo);


                return AjaxResult.success(userInfo);
            }
        }
        return AjaxResult.fail(0, null);


    }

    @RequestMapping("/showinfo")
    public AjaxResult showInfo(HttpServletRequest request) {
        UserInfoVO userInfoVO = new UserInfoVO();
        UserInfo userInfo = UserSessionUtils.getUserSession(request);
        if (userInfo == null) {
            return AjaxResult.fail(-1, "非法请求");

        }
        BeanUtils.copyProperties(userInfo, userInfoVO);
        userInfoVO.setArtCount(articleService.getArtCountByUid(userInfoVO.getId()));
        return AjaxResult.success(userInfoVO);
    }

    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session) {
        session.removeAttribute(AppVariable.USER_SESSION_KEY);
        return AjaxResult.success(1);
    }

    @RequestMapping("/getuserbyid")
    public AjaxResult getUserById(Integer id) {
        if (id == null || id <= 0) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        UserInfo userInfo = userService.getUserById(id);
        if (userInfo == null || userInfo.getId() <= 0) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        BeanUtils.copyProperties(userInfo, userInfoVO);
        userInfoVO.setArtCount(articleService.getArtCountByUid(id));
        return AjaxResult.success(userInfoVO);
    }

    @RequestMapping("/getcode")
    public AjaxResult ImgCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 服务器通知浏览器不要缓存
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");
        //自定义图形验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 40, 4, 5);
        // 得到生成的图形验证码
        String code = captcha.getCode();
        //将验证码 存储到redis中
        stringRedisTemplate.opsForValue().set("code", code);
        stringRedisTemplate.expire("code", 5, TimeUnit.MINUTES);

        System.out.println("验证码：" + code);

        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        outputStream.close();
        return AjaxResult.success(outputStream);

    }
}
